package actions;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPopupMenu;
import javax.swing.JTextPane;

import textArea.AwesomeTextPanel;

import frame.AwesomeFrame;

/**
 * AwesomeKeyActions should be used for actions that will occur when a key is typed
 * in a JTextPane.
 * 
 * Ideally the source of the ActionEvent passed by the actionPerformed
 * will be the JTextPane this Action will manipulate.
 *
 */
public abstract class AwesomeKeyAction implements ActionListener {
	
	/**
	 * The name can be used for debugging or testing.
	 */
	private String name;

	public AwesomeKeyAction(String name) {
		this.name = name;
	}
	
	/**
	 * Returns the name of this AwesomeKeyAction
	 * @return the name of this AwesomeKeyAction
	 */
	public String getName() {
		return this.name;
	}
	
	/**
	 * Returns the JTextPane associated with this Key Action.
	 * @param e The ActionEvent which invoked this Aciton.
	 * @return the JTextPane associated with this Key Action.
	 * 
	 * Ideally the source of the ActionEvent will be the JTextPane this Action will manipulate.
	 */
	protected JTextPane getTextPane(ActionEvent e) {
		if ( e != null ) {
			if ( e.getSource() instanceof JTextPane ) {
				return (JTextPane)e.getSource();
			}
		}
		return null;
	}
	
	
	/**
	 * Returns the parent AwesomeTextPanel of the source which invoked this action.
	 * @param e The ActionEvent that invoked this action.
	 * @return the parent AwesomeTextPanel of the source which invoked this action.
	 */
	protected AwesomeTextPanel getParentAwesomeTextPanel(ActionEvent e) {
		if (e != null) {
			Object source = e.getSource();
			
			// Surely the source is a component, but we should be sure when casting.
			// We must cast to a component to navigate to the parent of source.
			if (source instanceof Component) {
				
				Component current = (Component) source;
				// Loop until we locate the frame.
				while (true) {
					if ( current == null ) {
						break;
					} else if ( current instanceof AwesomeTextPanel ) {
						return (AwesomeTextPanel) current;
					} else {
						current = current.getParent();
					}
				}
			}
		}
		return null;
	}
}
